package middle;

public class Solution_61 {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        int count = 0;
        ListNode node = head;
        while (node != null) {
            count++;
            node = node.next;
        }
        k = k % count;
        if (k == 0) {
            return head;
        }
        ListNode firstHeader = null, secondEnd = head;
        int num = count - k;
        for (int i = 1; i < num; i++) {
            secondEnd = secondEnd.next;
        }
        firstHeader = secondEnd.next;
        secondEnd.next = null;

        if (firstHeader == null) {
            return head;
        } else {
            ListNode rst = firstHeader;
            while (firstHeader.next != null) {
                firstHeader = firstHeader.next;
            }
            firstHeader.next = head;
            return rst;
        }
    }

    static class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }

    public static void main(String[] args) {
        Solution_61 model = new Solution_61();
        ListNode header = new ListNode(1);
        header.next = new ListNode(2);
        header.next.next = new ListNode(3);
        header.next.next.next = new ListNode(4);
        header.next.next.next.next = new ListNode(5);
        ListNode listNode = model.rotateRight(header, 6);
        System.out.println();
    }
}
